<template>
  <div class="user-layout-register">
    <div class="login-content">
      <div>后台管理系统</div>
      <div class="bottom-title">
        <span style="margin-right: 38px">品质源于关注</span>
        <span>创新引领未来</span>
      </div>
    </div>
    <a-form-model
      ref="form"
      class="login-form"
      :model="form"
      :rules="rules"
      :hideRequiredMark="hideRequiredMark">
      <a-alert
        v-if="isRegisterError"
        type="error"
        showIcon
        style="margin-bottom: 24px;"
        :message="registerErrorInfo"
        closable
        :after-close="handleCloseRegisterError"
      />
      <h3 class="title">注册</h3>
      <a-form-model-item prop="username" label="账号">
        <a-input
          v-model="form.username"
          size="large"
          autocomplete="off"
          placeholder="请输入账户">
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-model-item>
      <a-form-model-item has-feedback prop="password" label="密码">
        <a-input-password v-model="form.password" autocomplete="off" size="large" placeholder="请输入密码">
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input-password>
      </a-form-model-item>
      <a-form-model-item has-feedback prop="confirmPassword" label="确认密码">
        <a-input-password
          v-model="form.confirmPassword"
          autocomplete="off"
          size="large"
          placeholder="确认密码"
          :maxLength="20" >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input-password>
      </a-form-model-item>
      <a-form-model-item prop="code" label="验证码" v-if="captchaEnabled">
        <a-input v-model="form.code" size="large" type="text" autocomplete="off" placeholder="验证码">
          <a-icon slot="prefix" type="security-scan" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          <img slot="suffix" class="getCaptcha" :src="codeUrl" @click="getCode">
        </a-input>
      </a-form-model-item>
      <a-form-item>
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="register-button"
          :loading="registering"
          @click.stop.prevent="handleRegister"
          :disabled="registering"
        >
          <span v-if="!registering">注 册</span>
          <span v-else>注 册 中...</span>
        </a-button>
        <div style="float: left">
          <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
        </div>
      </a-form-item>
    </a-form-model>
  </div>
</template>

<script>
import { getCodeImg, register } from '@/api/login'
export default {
  name: 'Register',
  components: {},
  data () {
    const validateNewPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else if (!/^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$)([^\u4e00-\u9fa5\s]){5,20}$/.test(value)) {
        callback(new Error('请输入5-20位英文字母、数字或者符号（除空格），且字母、数字和标点符号至少包含两种'))
      } else {
        if (this.form.confirmPassword !== '') {
          this.$refs.form.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码确认'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      codeUrl: '',
      isRegisterError: false,
      hideRequiredMark: true,
      registerErrorInfo: '',
      form: {
        username: undefined,
        password: undefined,
        confirmPassword: undefined,
        code: undefined,
        uuid: undefined
      },
      rules: {
        username: [
          { required: true, trigger: 'blur', message: '请输入您的账号' },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
          { required: true, validator: validateNewPass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', message: '请再次输入您的密码' },
          { required: true, validator: validateConfirmPass, trigger: 'blur' }
        ],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
      },
      registerBtn: false,
      registering: false,
      captchaEnabled: true
    }
  },
  computed: {},
  created () {
    this.getCode()
  },
  methods: {
    getCode () {
      getCodeImg().then((res) => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.form.uuid = res.uuid
        }
      })
    },
    handleRegister () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.registering = true
          register(this.form)
            .then(res => this.registerSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              this.registering = false
            })
        } else {
          setTimeout(() => {
            this.registering = false
          }, 600)
        }
      })
    },
    registerSuccess (res) {
      this.$router.push({ path: '/login' })
      // 延迟 1 秒显示欢迎信息
      const username = this.form.username
      setTimeout(() => {
        this.$notification.success({
          message: '恭喜你，您的账号 ' + username + ' 注册成功！'
        })
      }, 1000)
      this.handleCloseRegisterError()
    },
    requestFailed (err) {
      this.isRegisterError = true
      this.registerErrorInfo = err
      this.form.code = undefined
      if (this.captchaEnabled) {
        this.getCode()
      }
    },
    handleCloseRegisterError () {
      this.isRegisterError = false
      this.registerErrorInfo = ''
    }
  }
}
</script>
<style lang="less">
.user-register {
  &.error {
    color: #ff0000;
  }
  &.warning {
    color: #ff7e05;
  }
  &.success {
    color: #52c41a;
  }
}
.user-layout-register {
  .ant-input-group-addon:first-child {
    background-color: #fff;
  }
}
</style>
<style lang="less" scoped>

.ant-form-item{
  margin-bottom: 10px;
}
::v-deep .ant-input-affix-wrapper .ant-input{
  border-radius: 10px;
}
.user-layout-register{
  display: flex;
  position: relative;
  justify-content: center;
  align-items: center;
  height: 100vh;
  //background-image: url("../assets/loginImage/background.png");
  background-image: url("../../assets/background.png");
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  & > h3 {
    font-size: 16px;
    margin-bottom: 20px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }
  .login {
    float: right;
    line-height: 40px;
  }
  .login-content {
    align-self: flex-start;
    justify-self: flex-start;
    margin-left: -40.2%;
    font-size: 91px;
    font-weight: 700;
    letter-spacing: 10px;
    color: #152f86;
    margin-top: 50px;
    .bottom-title {
      margin-top: 32px;
      padding-left: 45px;
      font-size: 36px;
      letter-spacing: 2.6px;
    }
  }
  // .el-button {
  //   margin-top: 28px;
  //   width: 100%;
  //   height: 44px;
  //   line-height: 12px;
  //   background-color: #0452fe;
  // }
}
.title {
  font-size: 50px;
  font-weight: 700;
  // margin: 0px auto 22px auto;
  margin-right: -18px;
  margin-bottom: 20px;
  text-align: center;
  letter-spacing: 16.3px;
  white-space: nowrap;
}

.login-form {
  position: absolute;
  right: 10.2%;
  top: 45.2%;
  transform: translateY(-50%);
  border-radius: 6px;
  width: 22.7%;
  padding: 25px 25px 5px 25px;
  label {
    font-size: 14px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 32px;
    margin: 4px 0;
  }
  .register {
    float: right;
  }
  button.register-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
</style>
